package com.lemon.smartsafety.ui.fragment.news;

import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.entity.event.news.NewsSearchEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.http.service.NewsInfoServices;
import com.lemon.smartsafetynew.ui.fragment.base.BaseFragment;
import com.lemon.smartsafetynew.ui.fragment.base.ToolbarBaseFragment;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.safecloud.greendao.NewsColumn;

import org.greenrobot.eventbus.Subscribe;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;

/**
 * Created by Cooliean on 16/1/19.
 */
public class NewsFragment extends ToolbarBaseFragment implements SearchView.OnQueryTextListener {


    @Bind(R.id.tabs)
    TabLayout mTablayout;
    @Bind(R.id.viewPager)
    ViewPager mViewPager;

    FragmentStatePagerAdapter mViewPagerAdapter;


    private   MenuItem   searchItem;
    protected SearchView mSearchView;
    private LoggerHelper loggerHelper = new LoggerHelper(NewsFragment.class);

    private int mPosition = -1;


    private List<NewsColumn> mItems = new ArrayList<>();


    private Map<String, BaseFragment> mBaseFragmentMap = new HashMap<>();

    @Override
    protected int getTitle() {
        return R.string.draw_news;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_news_fragment;
    }


    @Override
    protected void getBaseArguments() {
        super.getBaseArguments();
        if (getArguments() != null) {
            mPosition = getArguments().getInt(BundleKey.NEWS_COLUMN_POSITION, -1);
        }
    }


    public static NewsFragment newInstance(int position) {
        Bundle args = new Bundle();
        args.putInt(BundleKey.NEWS_COLUMN_POSITION, position);
        NewsFragment pageFragment = new NewsFragment();
        pageFragment.setArguments(args);
        return pageFragment;
    }


    @Override
    protected void initViews() {
        super.initViews();
        initSearchView();
        if (mItems.size() == 0) {
            getNetData();
        }
    }


    private void initSearchView() {
        SearchManager searchManager = (SearchManager) getContext().getSystemService(Context.SEARCH_SERVICE);
        mSearchView = new SearchView(((AppCompatActivity) getActivity()).getSupportActionBar().getThemedContext());
        mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
        mSearchView.setIconifiedByDefault(true);
        mSearchView.setMaxWidth(1000);
        SearchView.SearchAutoComplete searchAutoComplete = (SearchView.SearchAutoComplete) mSearchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
        searchAutoComplete.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                //if (!hasFocus) showSearch(false);
            }
        });
        searchAutoComplete.setHintTextColor(getResources().getColor(R.color.material_grey_300));
        searchAutoComplete.setTextColor(getResources().getColor(R.color.colorWhite));
        searchAutoComplete.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.common_text_size));
        searchAutoComplete.setHint(getResources().getString(R.string.search_common_hit));
        searchAutoComplete.setBackgroundResource(R.mipmap.edit_white_bg);

        searchAutoComplete.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                //if (!hasFocus) showSearch(false);
            }
        });
        try {
            // This sets the cursor
            // resource ID to 0 or @null
            // which will make it visible
            // on white background
            Field mCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
            mCursorDrawableRes.setAccessible(true);
            mCursorDrawableRes.set(searchAutoComplete, 0);

        } catch (Exception e) {
            e.printStackTrace();
        }
        mSearchView.setOnQueryTextListener(this);
    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        searchItem = menu.add(android.R.string.search_go);
        searchItem.setIcon(R.mipmap.ic_search_white_24dp);

        MenuItemCompat.setActionView(searchItem, mSearchView);

        MenuItemCompat.setShowAsAction(searchItem, MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
    }


    private void getNetData() {
        NewsInfoServices.init().getNewsColumn();
    }

    /**
     * http处理请求的处理
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(HttpCallbackEvent event) {
        if (EventTag.TAG_MAIN_NEWS_COLUMN_HTTP.equals(event.getTag())) {//获取新闻分类
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                mHUDUtil.hidden();
                List<NewsColumn> colNews = (List<NewsColumn>) event.getObj();
                if (colNews != null && colNews.size() != 0) {
                    mItems.clear();
                    mItems.addAll((List<NewsColumn>) event.getObj());
                    setUpViewPager(mItems);
                }
//                if (event.getEventResult() == Constants.Result.SUCCESS) {
//                    mItems.clear();
//                    mItems.addAll((List<NewsColumn>) event.getObj());
//                    setUpViewPager(mItems);
//                } else {
//                    mHUDUtil.showErrorTip(event.getMsg());
//                }
            }
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //        if (mItems != null && mItems.size() != 0) {
        //
        //        }else{
        //            getNetData();
        //        }
    }


    private TabLayout.TabLayoutOnPageChangeListener tabLayoutOnPageChangeListener = new TabLayout.TabLayoutOnPageChangeListener(mTablayout) {
        @Override
        public void onPageSelected(int position) {
            super.onPageSelected(position);
            mPosition = position;
        }
    };

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    private void setUpViewPager(final List<NewsColumn> items) {
        final String[] titles = new String[items.size()];
        for (int i = 0; i < items.size(); i++) {
            titles[i] = items.get(i).getTitle();
        }
        if (titles.length > 4) {//这里设置缩放
            mTablayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        }
        mViewPagerAdapter = new FragmentStatePagerAdapter(getActivity().getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return getFragment(position);
            }

            @Override
            public int getCount() {
                return titles.length;
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return titles[position];
            }

        };


        mViewPager.setOffscreenPageLimit(2);


        mViewPager.setAdapter(mViewPagerAdapter);

        mViewPager.setOnPageChangeListener(tabLayoutOnPageChangeListener);


        if (mPosition != -1) {
            mViewPager.setCurrentItem(mPosition);
        }

        mTablayout.setupWithViewPager(mViewPager);

    }

    private BaseFragment getFragment(int position) {
        if (mBaseFragmentMap == null) {
            return NewsContent.newInstance(mItems.get(position).getVoId());
        }
        BaseFragment baseFragment = mBaseFragmentMap.get(position + "");
        if (baseFragment == null) {
            try {
                baseFragment = NewsContent.newInstance(mItems.get(position).getVoId());
            } catch (Exception e) {
                e.printStackTrace();
                baseFragment = NewsContent.newInstance(mItems.get(position).getVoId());
            }
            mBaseFragmentMap.put(position + "", baseFragment);
        }
        return baseFragment;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        if (mSearchView != null) {
            // 得到输入管理对象
            InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) {
                // 这将让键盘在所有的情况下都被隐藏，但是一般我们在点击搜索按钮后，输入法都会乖乖的自动隐藏的。
                // 输入法如果是显示状态，那么就隐藏输入法
                imm.hideSoftInputFromWindow(mSearchView.getWindowToken(), 0);
            }
            // 不获取焦点
            mSearchView.clearFocus();
            showSearch(false);

            if (mViewPager != null) {
                NewsColumn      itemVo = mItems.get(mViewPager.getCurrentItem());
                NewsSearchEvent event  = new NewsSearchEvent();
                event.setTag(NewsSearchEvent.class.getName() + itemVo.getVoId());
                event.setColumnId(itemVo.getVoId());
                event.setData(query);
                AppService.getBus().post(event);
            }


        }
        // 修改为false，你看，你自己的代码注释里，已经对返回值做了说明呀！！！
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        return false;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mBaseFragmentMap = null;
    }

    public void showSearch(boolean visible) {
        if (visible) MenuItemCompat.expandActionView(searchItem);
        else MenuItemCompat.collapseActionView(searchItem);
    }
}
